/* 
    Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
    Use of this sample source code is subject to the terms of the Microsoft license 
    agreement under which you licensed this sample source code and is provided AS-IS.
    If you did not accept the terms of the license agreement, you are not authorized 
    to use this sample source code.  For the terms of the license, please see the 
    license agreement between you and Microsoft.
  
    To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604 
  
*/
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;

namespace sdkSoundCS
{
    public partial class MainPage : PhoneApplicationPage
    {
        // The sounds to play
        private SoundEffect coyoteSound;
        private SoundEffect birdSound;

        // Use MediaElement to loop, pause, and resume the ambience sound.
        // Certification requirement 6.5.4 (http://go.microsoft.com/fwlink/?LinkID=22163) 
        // says we can't use SoundEffect for a continuous background track.
        private MediaElement ambienceSound;

        // Flag that indicates if we need to resume Zune playback upon exiting.
        bool resumeMediaPlayerAfterDone = false;


        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Timer to simulate the XNA game loop (SoundEffect class is from the XNA Framework)
            GameTimer gameTimer = new GameTimer();
            gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);

            // Call FrameworkDispatcher.Update to update the XNA Framework internals.
            gameTimer.Update += delegate { try { FrameworkDispatcher.Update(); } catch { } };

            // Start the GameTimer running.
            gameTimer.Start();

            // Prime the pump or we'll get an exception.
            FrameworkDispatcher.Update();

            // Create and load SoundEffect objects.
            LoadSound("Resources/coyoteSound.wav", out coyoteSound);
            LoadSound("Resources/birdSound.wav", out birdSound);

            // Create a MediaElement to play the background sound.
            // See the Application Certification Requirements section 6.5.4
            // (http://go.microsoft.com/fwlink/?LinkID=22163) for more information 
            // about using MediaElement instead of SoundEffect here.
            ambienceSound = new MediaElement();
            ambienceSound.AutoPlay = true;
            ambienceSound.Source = new Uri("Resources/ambienceSound.wav", UriKind.Relative);
            ambienceSound.Volume = 0.8f;
            ambienceSound.MediaEnded += new RoutedEventHandler(ambienceSound_MediaEnded);
            LayoutRoot.Children.Add(ambienceSound);
            ambienceSound.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Loads a wav file into an XNA Framework SoundEffect.
        /// </summary>
        /// <param name="SoundFilePath">Relative path to the wav file.</param>
        /// <param name="Sound">The SoundEffect to load the audio into.</param>
        private void LoadSound(String SoundFilePath, out SoundEffect Sound)
        {
            // For error checking, assume we'll fail to load the file.
            Sound = null;

            try
            {
                // Holds informations about a file stream.
                StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));

                // Create the SoundEffect from the Stream
                Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
                
            }
            catch (NullReferenceException)
            {
                // Display an error message
                MessageBox.Show("Couldn't load sound " + SoundFilePath);
            }
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // If the MediaPlayer is already playing music, pause it upon entering our app.
            ZunePause();
        }
        

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // If the MediaPlayer was already playing music, resume playback as we leave our app.
            ZuneResume();
        }

        
        /// <summary>
        /// Plays the coyote sound when the button is clicked.
        /// </summary>
        private void coyoteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                coyoteSound.Play();
               


            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Can't play, coyoteSound is null.");
            }
        }

        /// <summary>
        /// Plays the bird sound when the button is clicked.
        /// </summary>
        private void birdButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                birdSound.Play();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Can't play, birdSound is null.");
            }
        }

        /// <summary>
        /// Starts or resumes the ambience background sound when the check box is checked.
        /// </summary>
        private void ambienceCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (ambienceSound != null)
            {
                ambienceSound.Play();
            }
        }

        /// <summary>
        /// Pauses the ambience background sound when the check box is unchecked.
        /// </summary>
        private void ambienceCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ambienceSound.CurrentState == MediaElementState.Playing)
                {
                    ambienceSound.Pause();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("Can't pause, ambienceSound is null.");
            }
        }

        /// <summary>
        /// Resets the MediaElement back to the beginning and starts 
        /// playing again, creating a looping background sound.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ambienceSound_MediaEnded(object sender, RoutedEventArgs e)
        {
            // Loop the ambience sound.
            ambienceSound.Position = TimeSpan.Zero;
            ambienceSound.Play();
        }

        #region Zune Pause/Resume

        private void ZunePause()
        {
            // Please see the MainPage() constructor above where the GameTimer object is created.
            // This enables the use of the XNA framework MediaPlayer class by pumping the XNA FrameworkDispatcher.

            // Pause the Zune player if it is already playing music.
            if (!MediaPlayer.GameHasControl)
            {
                MediaPlayer.Pause();
                resumeMediaPlayerAfterDone = true;
            }
        }

        private void ZuneResume()
        {
            // If Zune was playing music, resume playback
            if (resumeMediaPlayerAfterDone)
            {
                MediaPlayer.Resume();
            }
        }

        #endregion Zune Pause/Resume
    
    }
}
